package com.module.ble.hDu

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.os.Build
import android.util.Log
import net.grandcentrix.tray.AppPreferences
import java.util.Locale
import java.util.UUID

object HDSysUtils {

    /**
     * 第二种
     * 执行配对 官方API
     * @param bluetoothDevice  蓝牙设备
     * @return  true 执行绑定 false 未执行绑定
     */
    @SuppressLint("ObsoleteSdkInt")
    fun boundDeviceAPI(bluetoothDevice: BluetoothDevice?): Boolean {
        if (bluetoothDevice == null) {
            return false
        }
        //注意：Android 4.4版本之后的API
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            try {
                val m =
                    bluetoothDevice.javaClass.getMethod("createBond", Int::class.javaPrimitiveType)
                val value = m.invoke(bluetoothDevice, BluetoothDevice.TRANSPORT_BREDR)
                return value as Boolean
            } catch (e: Exception) {
                Log.e("createBond failed", e.message!!)
            }
        }
        return bluetoothDevice.createBond()
    }

    /**
     * 取消设备配对
     */
    fun removeBoundDevice(bluetoothDevice: BluetoothDevice?): Boolean {
        if (bluetoothDevice == null) {
            return false
        }
        //注意：Android 4.4版本之后的API
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                val m = bluetoothDevice.javaClass.getMethod("removeBond")
                val value = m.invoke(bluetoothDevice)
                return value as Boolean
            } catch (e: Exception) {
                Log.e("createBond failed", e.message!!)
            }
        }
        return false
    }

    fun printHexString(bytes: ByteArray?): String {
        if (bytes == null) {
            return ""
        }

        var hexString = ""
        for (index in bytes.indices) {
            var hex = Integer.toHexString(bytes[index].toInt() and 0xFF)
            if (hex.length == 1) {
                hex = "0$hex"
            }
            hexString += hex.uppercase(Locale.getDefault()) + " "
        }

        return hexString
    }

    fun getPhoneUniqueId(sf: AppPreferences?): String {
        var uniqueID = sf?.getString(HDCommonAttributes.APP_UNIQUEID, "") ?: ""
        if (uniqueID.isEmpty()) {
            uniqueID = UUID.randomUUID().toString()
            sf?.put(HDCommonAttributes.APP_UNIQUEID, uniqueID)
        }
        return uniqueID
    }
}